const exec = require("../db/mysql")
const { SuccessModel, ErrorModel } = require("../model/resModel")
const register = (username, password, realname) => {
  if (username === "" || password === "" || realname === "") {
    return Promise.resolve(new ErrorModel("用户名/密码/姓名不能为空"))
  }
  const sql = `insert into user(username,password,realname)value("${username}","${password}","${realname}")`
  return exec(sql).then(result => {
    if (result.affectedRows > 0) {
      return new SuccessModel("注册成功")
    } else {
      return new ErrorModel("注册失败")
    }
  })
}

const login = (username, password) => {
  const sql = `select * from user where username="${username}" and password="${password}"`
  return exec(sql).then(result => {
    if (result.length) {
      return new SuccessModel({ username: result[0].username, realname: result[0].realname }, "登录成功")
    } else {
      return new ErrorModel("登录失败")
    }
  })
}

module.exports = {
  login,
  register
}